package com.zyx.juc.cf.my;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Yaxi.Zhang
 * @since 2022/6/13 11:11
 */
public class CompletableFutureAllOfDemo3 {
    private static final AtomicInteger result = new AtomicInteger(0);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture[] futures = new CompletableFuture[10];

        for (int i = 0; i < 10; i++) {
            CompletableFuture<Void> myFuture = CompletableFuture.runAsync(() -> {
                try {
                    Thread.sleep(1000 + ThreadLocalRandom.current().nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                result.getAndIncrement();
            });
            futures[i] = myFuture;
        }

       CompletableFuture<Void> future = CompletableFuture.allOf(futures).thenRun(() -> System.out.println("计算完成"));

       future.get();
       System.out.println("=====>>>>> final result:" + result.get());
    }
}
